import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores'
import {
  insertCartService,
  getCartListService,
  deleteCartService,
  mergeCartService
} from '@/apis/cart'

export const useCartStore = defineStore(
  'rabbit-cart',
  () => {
    const cartList = ref([])
    const userStore = useUserStore()
    // 添加操作
    const isLogin = computed(() => userStore.userInfo.token)
    const addCart = async (good) => {
      // 接口购物车
      if (isLogin.value) {
        await insertCartService(good)
        getCartList()
        ElMessage.success('添加成功')
      } else {
        const item = cartList.value.find((i) => i.skuId === good.skuId)
        if (item) {
          item.count += good.count
        } else {
          cartList.value.push(good)
        }
      }
    }
    // 获取购物车商品
    const getCartList = async () => {
      if (isLogin.value) {
        const res = await getCartListService()
        cartList.value = res.data.result
      }
    }
    // 删除商品
    const deleteCart = async (skuId) => {
      // 接口删除
      if (isLogin.value) {
        await deleteCartService([skuId])
        getCartList()
      } else {
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
      }
      ElMessage.success('删除成功')
    }
    // 合并购物车
    const mergeCart = async () => {
      const cartInfo = cartList.value.map((item) => ({
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }))
      await mergeCartService(cartInfo)
      getCartList()
    }
    // 购物车统计计算
    // 商品总数
    const cartTotal = computed(() =>
      cartList.value.reduce((sum, item) => sum + item.count, 0)
    )
    // 商品总价
    const cartPrice = computed(() =>
      cartList.value
        .reduce((sum, item) => sum + item.count * item.price, 0)
        .toFixed(2)
    )
    // 已选择商品
    const selectedGoods = computed(() =>
      cartList.value.filter((item) => item.selected)
    )
    // 已选择商品数量
    const selectedCount = computed(() =>
      selectedGoods.value.reduce((sum, item) => sum + item.count, 0)
    )
    // 已选择商品价格
    const selectedPrice = computed(() =>
      selectedGoods.value
        .reduce((sum, item) => sum + item.count * item.price, 0)
        .toFixed(2)
    )
    // 购物车单选
    const singleCheck = () => cartList.value.every((item) => item.isChecked)
    // 购物车全选
    const allCheck = (val) => {
      cartList.value.forEach((item) => (item.selected = val))
    }
    const isAllChecked = computed(() =>
      cartList.value.every((item) => item.selected)
    )
    return {
      cartList,
      addCart,
      deleteCart,
      cartTotal,
      cartPrice,
      singleCheck,
      allCheck,
      isAllChecked,
      selectedCount,
      selectedPrice,
      selectedGoods,
      isLogin,
      getCartList,
      mergeCart
    }
  },
  {
    persist: true
  }
)
